<?php

namespace app\api\controller;

use app\payment\PayFactory;
use app\services\ConfigService;
use app\services\OrderService;
use plugin\admin\app\model\Order;
use support\Db;
use support\Log;
use support\Request;
use Yansongda\Pay\Pay;

class NotifyController
{
    public function handle(Request $request)
    {
        Db::beginTransaction();
        try {
            Pay::config(ConfigService::getPaymentConfig(PayFactory::WECHAT));

            $result = Pay::wechat()->callback($request->post())->toArray();

            if ($result['resource']['ciphertext']['trade_state'] == 'SUCCESS') {
                $orderNo = $result['resource']['ciphertext']['out_trade_no'];

                $order = Order::where('order_no', $orderNo)->first();

                if ($order['status'] == Order::STATUS_WAITING_PAY) {
                    switch ($order['type']) {
                        case Order::TYPE_GOODS:
                        case Order::TYPE_GIFT:
                            OrderService::paySuccess($orderNo);
                            break;
                    }
                }

                Db::commit();
                return Pay::wechat()->success();
            }

        } catch (\Exception $e) {
            Db::rollBack();
        }

    }

    public function handleAlipay(Request $request)
    {
        Db::beginTransaction();
        try {
            Pay::config(ConfigService::getPaymentConfig(PayFactory::ALIPAY));

            $result = Pay::alipay()->callback($request->post())->toArray();

            if ($result['trade_status'] == 'TRADE_SUCCESS') {
                $orderNo = $result['out_trade_no'];

                $order = Order::where('order_no', $orderNo)->first();

                if ($order['status'] == Order::STATUS_WAITING_PAY) {
                    switch ($order['type']) {
                        case Order::TYPE_GOODS:
                            OrderService::paySuccess($orderNo);
                            break;
                    }
                }

                Db::commit();
                return Pay::alipay()->success();
            }

        } catch (\Exception $e) {
            Log::info($e->getMessage() . $e->getTraceAsString());
            echo $e->getMessage() . $e->getTraceAsString();
            Db::rollBack();
        }

    }
}